/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.test_factory;

import static picounit.features.signature_factory.CollectionUtil.*;
import picounit.Lifecycle;
import picounit.features.test_instantiator.InvocationArgumentHandler;
import picounit.features.test_instantiator.Invoker;

import java.lang.reflect.InvocationTargetException;

public class LifecycleInvocationArgumentHandler implements InvocationArgumentHandler {
	private final Invoker invoker;
	
	public LifecycleInvocationArgumentHandler(Invoker invoker) {
		this.invoker = invoker;
	}
	
	public void preInvocation(Object[] arguments) throws IllegalAccessException, InvocationTargetException {
		for (Object argument : nullToEmpty(arguments)) {
			preInvocation(argument);
		}
	}

	public void postInvocation(Object[] arguments) throws IllegalAccessException, InvocationTargetException {
		for (Object argument : reverse(nullToEmpty(arguments))) {
			postInvocation(argument);
		}
	}
	
	///////////////////////////////////////////////////////////////////////////////////////////////
	// Implementation methods
	///////////////////////////////////////////////////////////////////////////////////////////////

	private void preInvocation(Object object) throws IllegalAccessException, InvocationTargetException {
		if (object instanceof Lifecycle) {
			invoker.invoke("setUp", object);
		}
	}

	private void postInvocation(Object object) throws IllegalAccessException, InvocationTargetException {
		if (object instanceof Lifecycle) {
			invoker.invoke("tearDown", object);
		}
	}
}
